#include "ComponentBoat.h"
#include "Components/ComponentDamage.h"
#include "Components/ComponentBody.h"

#include "Engine/MathUtils.hpp"
#include "Managers/EntityManager.h"
#include "Network/PackageManager.h"
#include "Network/Packages/ComponentHealthPackage.h"

#include "GameSingleton.h"
#include "GameRegistry.hpp"
#include "Log.h"
#include "GameThreadPool.hpp"


using namespace PocketSurvival::Engine;

namespace PocketSurvival
{
    void ComponentBoat::update(float dt)
    {
        if(componentDamage->hitpoints < 0.33f)
        {
            componentBody->density = 1.15f;
        }
        else if(componentDamage->hitpoints < 0.66f)
        {
            componentBody->density = 0.7f;
        }
        bool num = componentBody->immersionFactor > 0.95f;
        bool num2 = (false == num && componentBody->immersionFactor > 0.01f && componentBody->standingOnValue == 0 && componentBody->standingOnBody == nullptr);
        turnSpeed += 2.5f * dt * (1.0f * turnOrder - turnSpeed);

        Quaternion rotation;
        componentBody->getRotation(rotation);

        float num3 = MathUtils::Atan2<float>(2.0f * rotation.Y * rotation.W - 2.0f * rotation.X * rotation.Z, 1.0f - 2.0f * rotation.Y * rotation.Y - 2.0f * rotation.Z * rotation.Z);
        if(num2)
        {
            num3 -= turnSpeed * dt;
        }
        Quaternion::CreateFromAxisAngle(FastVector3::UnitY, num3, rotation);
        componentBody->setRotation(rotation);
        if(num2 && moveOrder != 0.0f)
        {
            Vector3 velocity;
            componentBody->getVelocity(velocity);
            velocity += dt * 3.0f * moveOrder * componentBody->getMatrix().getForward();
            componentBody->setVelocity(velocity);
        }
        if(num)
        {
            componentDamage->damage(0.005f * dt);

        }
        moveOrder = 0.0f;
        turnOrder = 0.0f;
    }

    static const std::string componentName = "Boat";
    const std::string &ComponentBoat::getName() const
    {
        return componentName;
    }
    const std::string &ComponentBoat::GetName()
    {
        return componentName;
    }

    void ComponentBoat::load(const nlohmann::json &jsonData)
    {
        componentBody = GameSingleton::gameRegistry->get<ComponentBody*>(entity);
        componentDamage = GameSingleton::gameRegistry->get<ComponentDamage*>(entity);
    }

} // namespace PocketSurvival
